'use client';

import { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, message, Modal, Form, Input, Radio, Select } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { 
  getNotifications, 
  createNotification, 
  updateNotification, 
  deleteNotification,
  setNotificationTopStatus,
  NotificationType, 
  NotificationStatus, 
  Notification,
  CreateNotificationParams,
  UpdateNotificationParams,
  TargetRole,
  Publisher
} from '@/services/notificationService';

// 导入shadcn组件
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

const { confirm } = Modal;
const { TextArea } = Input;
const { Option } = Select;

const AnnouncementsPage = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Notification[]>([]);
  const [selectedStatus, setSelectedStatus] = useState<NotificationStatus | undefined>(undefined);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingNotification, setEditingNotification] = useState<Notification | null>(null);
  const [form] = Form.useForm();
  
  // 删除确认对话框状态
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [notificationToDelete, setNotificationToDelete] = useState<Notification | null>(null);

  const fetchData = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      // 获取公告和通知类型的数据
      const [announcementResponse, noticeResponse] = await Promise.all([
        getNotifications({
          type: NotificationType.ANNOUNCEMENT,
          status: selectedStatus,
          page: page - 1,
          size: pageSize,
        }),
        getNotifications({
          type: NotificationType.NOTICE,
          status: selectedStatus,
          page: page - 1,
          size: pageSize,
        })
      ]);

      // 合并两种类型的数据
      const combinedContent = [
        ...announcementResponse.content,
        ...noticeResponse.content
      ].sort((a, b) => {
        // 首先按置顶状态排序
        if (a.isTop !== b.isTop) {
          return b.isTop ? 1 : -1;
        }
        // 然后按创建时间倒序排序
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
      });

      setData(combinedContent);
      setPagination({
        current: page,
        pageSize,
        total: announcementResponse.totalElements + noticeResponse.totalElements,
      });
    } catch (error) {
      message.error('获取通知公告列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [selectedStatus]);

  // 处理创建或更新通知
  const handleSubmit = async (values: any) => {
    try {
      console.log('表单提交的原始值:', values);
      
      if (editingNotification) {
        // 更新操作
        const updateParams: UpdateNotificationParams = {
          title: values.title,
          content: values.content,
          status: values.status,
          isTop: values.isTop,
          type: values.type || editingNotification.type,
          targetRole: values.targetRole || editingNotification.targetRole
        };
        
        console.log('更新操作 - ID:', editingNotification.id, '参数:', updateParams);
        console.log('isTop的值类型:', typeof updateParams.isTop, '值:', updateParams.isTop);
        
        await updateNotification(editingNotification.id, updateParams);
        message.success('更新成功');
      } else {
        // 创建操作
        const createParams: CreateNotificationParams = {
          title: values.title,
          content: values.content,
          type: values.type || NotificationType.ANNOUNCEMENT,
          status: values.status,
          isTop: false, // 创建时默认不置顶
          targetRole: values.targetRole || TargetRole.ALL,
          publisher: {
            id: 1 // TODO: 从用户上下文中获取当前用户ID
          }
        };
        
        console.log('创建操作 - 参数:', createParams);
        console.log('isTop的值类型:', typeof createParams.isTop, '值:', createParams.isTop);
        
        await createNotification(createParams);
        message.success('创建成功');
      }

      setIsModalVisible(false);
      form.resetFields();
      
      // 调用刷新函数而不是直接调用fetchData
      refreshData();
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    }
  };

  // 处理删除通知
  const handleDelete = (record: Notification) => {
    console.log('删除操作 - ID:', record.id, '通知详情:', record);
    
    // 设置要删除的通知并打开确认对话框
    setNotificationToDelete(record);
    setDeleteDialogOpen(true);
  };
  
  // 刷新数据
  const refreshData = () => {
    console.log('刷新数据');
    message.loading('正在刷新...', 0.5);
    fetchData(pagination.current, pagination.pageSize);
  };

  // 确认删除操作
  const confirmDelete = async () => {
    if (!notificationToDelete) return;
    
    try {
      message.loading('正在删除...', 0.5);
      
      // 修复：处理API响应可能为null或undefined的情况
      const result = await deleteNotification(notificationToDelete.id);
      console.log('删除结果:', result);
      
      // 无论返回什么结果，都认为删除成功
      message.success('删除成功');
      
      // 调用刷新函数
      refreshData();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    } finally {
      // 关闭对话框并清除要删除的通知
      setDeleteDialogOpen(false);
      setNotificationToDelete(null);
    }
  };

  // 处理置顶状态
  const handleToggleTop = async (record: Notification) => {
    try {
      const newIsTop = !record.isTop;
      console.log('置顶状态更新 - ID:', record.id, '新状态:', newIsTop);
      await setNotificationTopStatus(record.id, newIsTop);
      message.success(`${newIsTop ? '置顶' : '取消置顶'}成功`);
      fetchData(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('更新置顶状态失败:', error);
      message.error('操作失败');
    }
  };

  // 打开编辑或创建模态框
  const showModal = (record?: Notification) => {
    setEditingNotification(record || null);
    if (record) {
      // 编辑现有通知，设置表单初始值
      const initialValues = {
        title: record.title,
        content: record.content,
        status: record.status,
        isTop: record.isTop,
        type: record.type,
        targetRole: record.targetRole
      };
      
      form.setFieldsValue(initialValues);
      console.log('编辑通知 - 初始值:', initialValues);
      console.log('isTop初始值类型:', typeof initialValues.isTop, '值:', initialValues.isTop);
    } else {
      // 创建新通知，重置表单
      form.resetFields();
      // 设置默认值
      const defaultValues = {
        type: NotificationType.ANNOUNCEMENT,
        status: NotificationStatus.DRAFT,
        targetRole: TargetRole.ALL
      };
      
      form.setFieldsValue(defaultValues);
      console.log('创建通知 - 默认值:', defaultValues);
    }
    setIsModalVisible(true);
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: '25%',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '10%',
      render: (type: NotificationType) => (
        <Tag color={type === NotificationType.ANNOUNCEMENT ? 'blue' : 'cyan'}>
          {type === NotificationType.ANNOUNCEMENT ? '公告' : '通知'}
        </Tag>
      ),
    },
    {
      title: '发布者',
      dataIndex: ['publisher', 'name'],
      key: 'publisher',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: NotificationStatus) => (
        <Tag color={
          status === NotificationStatus.PUBLISHED ? 'green' :
          status === NotificationStatus.DRAFT ? 'gold' : 'red'
        }>
          {status === NotificationStatus.PUBLISHED ? '已发布' :
           status === NotificationStatus.DRAFT ? '草稿' : '已撤回'}
        </Tag>
      ),
    },
    {
      title: '置顶',
      dataIndex: 'isTop',
      key: 'isTop',
      render: (_: boolean, record: Notification) => (
        <Tag 
          color={record.isTop ? 'blue' : 'default'} 
          onClick={() => handleToggleTop(record)} 
          style={{ cursor: 'pointer' }}
        >
          {record.isTop ? '已置顶' : '未置顶'}
        </Tag>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'publishTime',
      key: 'publishTime',
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Notification) => (
        <Space size="middle">
          <Button type="link" onClick={() => showModal(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleTableChange = (pagination: any) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  return (
    <div>
      <div className="mb-4 flex justify-between items-center">
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
            新建公告
          </Button>
          <Select
            placeholder="选择状态"
            allowClear
            style={{ width: 120 }}
            onChange={(value) => setSelectedStatus(value)}
            value={selectedStatus}
          >
            <Option value={NotificationStatus.PUBLISHED}>已发布</Option>
            <Option value={NotificationStatus.DRAFT}>草稿</Option>
            <Option value={NotificationStatus.REVOKED}>已撤回</Option>
          </Select>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={refreshData}
            title="刷新数据"
          >
            刷新
          </Button>
        </Space>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />

      <Modal
        title={editingNotification ? '编辑公告' : '新建公告'}
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            type: NotificationType.ANNOUNCEMENT,
            status: NotificationStatus.DRAFT,
            targetRole: TargetRole.ALL
          }}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <Input.TextArea rows={6} placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Radio.Group>
              <Radio value={NotificationType.ANNOUNCEMENT}>公告</Radio>
              <Radio value={NotificationType.NOTICE}>通知</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="targetRole"
            label="目标角色"
            rules={[{ required: true, message: '请选择目标角色' }]}
          >
            <Radio.Group>
              <Radio value={TargetRole.ALL}>所有人</Radio>
              <Radio value={TargetRole.TEACHER}>教师</Radio>
              <Radio value={TargetRole.PARENT}>家长</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Radio.Group>
              <Radio value={NotificationStatus.DRAFT}>草稿</Radio>
              <Radio value={NotificationStatus.PUBLISHED}>发布</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 只在编辑模式下显示置顶选项 */}
          {editingNotification && (
            <Form.Item
              name="isTop"
              label="置顶"
              getValueFromEvent={(e) => {
                console.log('isTop选择事件:', e.target.value);
                return e.target.value;
              }}
              getValueProps={(value) => {
                console.log('isTop当前值:', value);
                return { value };
              }}
            >
              <Radio.Group>
                <Radio value={true}>置顶</Radio>
                <Radio value={false}>不置顶</Radio>
              </Radio.Group>
            </Form.Item>
          )}

          <Form.Item className="mb-0 text-right">
            <Space>
              <Button onClick={() => {
                setIsModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingNotification ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 添加shadcn的删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              {notificationToDelete ? `确定要删除"${notificationToDelete.title}"吗？此操作不可撤销。` : '确定要删除此通知吗？'}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
            <Button type="primary" danger onClick={confirmDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default AnnouncementsPage; 